//
//  RHHomeViewController.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/7/5.
//

#import "RHHomeViewController.h"

#import "RHHotProductCell.h"
#import "RHClassicCasesCell.h"
#import "RHNewProductCell.h"
#import "RHHomeCycleCell.h"
#import "RHHomeItemCell.h"
#import "RHNewProductListViewController.h"
#import "RHProductDetailViewController.h"
#import "RHBaseWebViewController.h"

#import "RHProductIntroduceVC.h"
#import "CDZQRScanViewController.h"
#import "NetworkConfig.h"
#import "RHNavigationController.h"
#import "AESCrypt.h"
#import "NSString+AES256.h"
#import "NSData+AES256.h"
#import "MIUAES.h"

@interface RHHomeViewController ()<SDCycleScrollViewDelegate,UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) QMUIButton         *selAddressBtn;



@property (nonatomic ,strong) UIScrollView       *bgScrollView;

@property (nonatomic ,strong) UITableView       *tableView;

@property (nonatomic ,strong) SDCycleScrollView * cycleScrollView;   // 轮播图 View

//@property (nonatomic ,strong) UICollectionView * collectionView;

@property (nonatomic ,strong) NSMutableArray * imageMuArr;// 轮播图片数组


@end

@implementation RHHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    [self setupUI];
    [self getHomeData];
    
    //Renon_Private
    NSString *ori = @"email:123456@163.com";
    
    NSString *encry = [AESCrypt encrypt:ori password:AES_key];
    NSString *encry1 = [ori aes256_encrypt:AES_key];
    NSString *encry2 = [MIUAES MIUAESEncrypt:ori mode:MIUModeECB key:AES_key keySize:MIUKeySizeAES128 iv:AES_IV padding:MIUCryptorPKCS7Padding];
    
    
    NSString *decry = [AESCrypt decrypt:encry password:AES_key];
    
    NSLog(@"---->原文:%@",ori);
    NSLog(@"---->加密后:%@",encry);
    NSLog(@"---->加密后1:%@",encry1);
    NSLog(@"---->加密后2:%@",encry2);
    NSLog(@"---->解密后:%@",decry);
   
}

-(void)getHomeData
{
    [BaseModel startGetWithCompletionAPIKey:H_homeData argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        [self.tableView endHeaderRefresh];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

- (void)setupUI{
    
    [self setupNavUI];
 
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    //_tableView.bounces = NO;
    //_tableView.scrollEnabled = NO;
    //_tableView.userInteractionEnabled = YES;
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    
    [_tableView registerClass:[RHHomeCycleCell class] forCellReuseIdentifier:@"RHHomeCycleCell"];
    [_tableView registerClass:[RHHomeItemCell class] forCellReuseIdentifier:@"RHHomeItemCell"];
    [_tableView registerClass:[RHHotProductCell class] forCellReuseIdentifier:@"HotProductCell"];
    [_tableView registerClass:[RHNewProductCell class] forCellReuseIdentifier:@"NewProductCell"];
    [_tableView registerClass:[RHClassicCasesCell class] forCellReuseIdentifier:@"ClassicCasesCell"];
    [self.view addSubview:_tableView];
    
    kWeakSelf;
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];

    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
   
    [self.tableView addHeaderRefresh:^{
        [weakSelf getHomeData];
    }];

}

- (void)setupNavUI{
    
    if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeNormalUser){
        UIBarButtonItem *scanBtn = [UIBarButtonItem itemWithImage:@"input_scan_icon" ImageHighLight:@"input_scan_icon" Target:self Seletor:@selector(scanQRC) CGRect:CGRectMake(0, 0, 30, 30)];
        
        self.navigationItem.rightBarButtonItem = scanBtn;
    }
    
}


#pragma mark - Action 国家代理申请
- (void)itemAction:(NSInteger)index{
    if(index == 1){
        //普通用户才可以申请
        if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeNormalUser){
            //判断自己有没有提交过申请,如果有提交过就不能往下走
            [QMUITips showLoading:@"checking..." inView:self.view];
            [BaseModel startGetWithCompletionAPIKey:H_getMyApply argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                if(resultModel.code == 200){
                    if ([request.responseObject[@"data"][@"apply"] integerValue] == 1) {

                    }else{
                        [QMUITips showError:@"You have already submitted an application"];
                    }
                }
                
                
            } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                
            }];
            
        }else{
            [QMUITips showError:@"You have already applied for it"];
        }
    }
    
    
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return section == 3 ?2:1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        RHHomeCycleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHHomeCycleCell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        kWeakSelf;
        cell.selectBlock = ^(NSInteger idx) {
            RHNewProductListViewController *VC = [[RHNewProductListViewController alloc]init];
            [weakSelf.navigationController pushViewController:VC animated:YES];
        };
        return cell;
    }
//    else if(indexPath.section == 1){
//        RHHomeItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHHomeItemCell"];
//        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
//        kWeakSelf;
//        cell.itemActionBlock = ^(NSInteger index) {
//            [weakSelf itemAction:index];
//        };
//        return cell;
//    }
    else if (indexPath.section == 1){
        RHNewProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewProductCell"];
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }else if (indexPath.section == 2){
        RHHotProductCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HotProductCell"];
        kWeakSelf;
        cell.selectItemBlock = ^(NSInteger itemIdx) {
            RHNewProductListViewController *VC = [[RHNewProductListViewController alloc]init];
            VC.navigationItem.title = @"热销产品".rh_localized;
            [weakSelf.navigationController pushViewController:VC animated:YES];
        };
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }
    
    RHClassicCasesCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ClassicCasesCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    NSString *imgName = [NSString stringWithFormat:@"home_classic%02zd",indexPath.row+1];
    [cell setImageName:imgName];
    
    return cell;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = kView;
    NSArray *titles = @[@"",@"新品发布".rh_localized,@"热销产品".rh_localized,@"经典案例".rh_localized];
    UILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.text = @"Qualification certification";
    titleLab.font = kBOLDSYSTEMFONT(15);
    titleLab.textColor = kColorRGB(123, 123, 123);
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.text = titles[section];
    [headView addSubview:titleLab];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headView).offset(15);
        make.centerY.equalTo(headView);
     }];
    
    if(section == 1){
        
        QMUIButton *moreBtn = [[QMUIButton alloc]init];
        [moreBtn setTitle:@"更多".rh_localized forState:UIControlStateNormal];
        [moreBtn setTitleColor:CFMainColor forState:UIControlStateNormal];
        moreBtn.titleLabel.font = kSYSTEMFONT(12);
        [moreBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        [headView addSubview:moreBtn];
        [moreBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
            make.centerY.equalTo(headView);
            make.right.mas_equalTo(-15);
            make.width.mas_equalTo(80);
        }];
        kWeakSelf;
        [[moreBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            
            RHNewProductListViewController *VC = [[RHNewProductListViewController alloc]init];
            [weakSelf.navigationController pushViewController:VC animated:YES];
                    
        }];
    }
   
   return  section <1 ? nil:headView;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return section <1 ? 10.0:55.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return  section == 0? nil:[UIView new];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 0){
        RHNewProductListViewController *VC = [[RHNewProductListViewController alloc]init];
        [self.navigationController pushViewController:VC animated:YES];
    }else if(indexPath.section == 3){
        RHProductIntroduceVC *vc = [[RHProductIntroduceVC alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        RHNewProductListViewController *VC = [[RHNewProductListViewController alloc]init];
        [self.navigationController pushViewController:VC animated:YES];
    }
}



#pragma mark ----- 检查二维码信息 ----------
-(void)checkContent:(NSString *)content
{
    NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error= nil;
    NSDictionary *dicInfo = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if (![dicInfo isKindOfClass:[NSDictionary class]]){
        [QMUITips showError:@"数据错误".rh_localized];
        return;
    }

    
    [QMUITips showLoadingInView:self.view];
    [BaseModel startGetWithCompletionAPIKey:H_parsingInvitationCodes argument:@{@"invitationCode":dicInfo[@"QRCode"]} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
           
                kWeakSelf;
                QMUIAlertController *alertVC = [QMUIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"%@ %@ ?",@"绑定用户".rh_localized,request.responseJSONObject[@"data"][@"email"]] preferredStyle:QMUIAlertControllerStyleAlert];
                
                [alertVC addAction:[QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
                    [QMUITips showLoadingInView:weakSelf.view];
                    [BaseModel startWithCompletionAPIKey:H_bindSuper argument:@{@"sendEmail":request.responseJSONObject[@"data"][@"email"]} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                        if(resultModel.code == 200){
                            
                            [QMUITips showSucceed:@"绑定用户成功".rh_localized inView:self.view hideAfterDelay:1];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                //绑定成功后获取一下个人信息,根据角色重新加载对应控制器
                                [QMUITips showLoadingInView:weakSelf.view];
                                [[PrivateMange share]getUserInfoSuccess:^(RHUserModel * _Nonnull userModel) {
                                    [[NSNotificationCenter defaultCenter]postNotificationName:UserRoleDidChangeNotification object:nil];
                                }];
                            });
                        }
                        
                        
                    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                                
                    }];
                    
                }]];
                [alertVC addAction:[QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleDefault handler:nil]];
                [alertVC showWithAnimated:YES];
           
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
 
   
}


#pragma mark ------ 扫描二维码

- (void)scanQRC{
    if ([self isCameraAvailable]) {
        [self isCanVisitPhotoAndCameraAuthorization:^(BOOL isOK,NSString *alerStr) {
            if (isOK) {
                NSLog(@"权限OK");
                kWeakSelf;
                CDZQRScanViewController *controller = [[CDZQRScanViewController alloc] init];
                controller.resultCallBack = ^(NSString *content) {
                    [weakSelf checkContent:content];
                };
                 RHNavigationController *nav = [[RHNavigationController alloc] initWithRootViewController:controller];
                [nav setModalPresentationStyle:UIModalPresentationOverFullScreen];
                [self presentViewController:nav animated:YES completion:^{
                    
                }];
            }else{
                if (alerStr) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:alerStr preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"去设置".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                         if (@available(iOS 10.0, *)) {
                             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                             } else {
                             NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                             if ([[UIApplication sharedApplication] canOpenURL:url]) {
                                 [[UIApplication sharedApplication] openURL:url];
                             }
                         }
                    }];
                    
                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSLog(@"点击了取消按钮");
                    }];
                    [alert addAction:cancel];
                    [alert addAction:conform];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }
        }];
    }else{
        NSLog(@"摄像头不可用");
    }

}

// 判断设备是否有摄像头
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
- (void)isCanVisitPhotoAndCameraAuthorization:(void(^)(BOOL isOK,NSString *alerStr))result {
    PHAuthorizationStatus photo_status = [PHPhotoLibrary authorizationStatus];
    AVAuthorizationStatus camera_status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (photo_status == PHAuthorizationStatusAuthorized&&camera_status ==AVAuthorizationStatusAuthorized) {
        result(YES,nil);
        return;
    }
    
    if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied||
        camera_status ==AVAuthorizationStatusDenied || camera_status ==AVAuthorizationStatusRestricted) {
        if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied) {
            result(NO,@"Please allow access photos in iPhone's Settings");
        }else{
            result(NO,@"Please allow access camera in iPhone's Settings");
        }
        return ;
    }
    
    if (camera_status == AVAuthorizationStatusNotDetermined) {
        //点击弹框授权
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(!granted){//不允许
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"未开启相机权限,请到设置中开启");
                    result(NO,nil);
                });
            }else{
                if (photo_status == PHAuthorizationStatusNotDetermined) {
                    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                               // 回调是在子线程的
                               NSLog(@"%@",[NSThread currentThread]);
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (status != PHAuthorizationStatusAuthorized) {
                                         NSLog(@"未开启相册权限,请到设置中开启");
                                         result(NO,nil);
                                   }else{
                                         result(YES,nil);
                                   }
                               });
                     
                           }];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        result(YES,nil);
                    });
                }

            }
        }];
        return;
    }
    
    if (photo_status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                   // 回调是在子线程的
                   NSLog(@"%@",[NSThread currentThread]);
                   dispatch_async(dispatch_get_main_queue(), ^{
                       if (status != PHAuthorizationStatusAuthorized) {
                             NSLog(@"未开启相册权限,请到设置中开启");
                             result(NO,nil);
                       }else{
                             result(YES,nil);
                       }
                   });
               }];
    }
}

@end
